import React from 'react'
import _ from 'underscore'
import View from 'lib/View.jsx'
import Card from 'lib/components/card.jsx'
import DetailScope from './DetailScope.es6'
import dispatcher from 'lib/dispatcher'
import cx from 'classnames'
import ChartWidget from 'lib/components/ChartWidget.jsx'
import Tab from 'lib/components/tab.jsx'
import moment from 'moment'
import numeral from 'numeral'

let setup = (item, func, defaultValue) => {
  if (item === null || item === undefined) {
    return defaultValue;
  } else {
    return func(item);
  }
};

const mb = 1024;
const gb = mb * 1024;

let storageDisplay = (value) => {
  if (value >= gb) {
    return numeral(value / gb).format('0[.]00') + ' GB';
  } else if (value >= mb) {
    return numeral(value / 1024).format('0[.]00') + ' MB';
  } else {
    return numeral(value).format('0[.]00') + ' KB';
  }
}

export default class DetailView extends View {

  constructor(props) {
    super(props);

    this.statusCodeChangeHandler = this.statusCodeChangeHandler.bind(this);
    this.customDateCheckHandler = this.customDateCheckHandler.bind(this);
  }

  statusCodeChangeHandler(e) {
    dispatcher.dispatch({
      $type:'change_status_code',
      value: parseInt(e.target.value)
    });
  }

  customDateCheckHandler(item) {
    dispatcher.dispatch({
      $type: 'custom_date_check',
      item: item
    });
  }

  dateCheckHandler(dayUnit) {
    dispatcher.dispatch({
      $type: 'predefined_date_check',
      dayUnit: dayUnit
    });
  }

  contentOffsetHandler(isAdd) {
    if (this.state.contentOffset === 0 && !isAdd) {
      return;
    }
    if (this.state.contentOffset === (this.state.model.count-1) && isAdd) {
      return;
    }

    dispatcher.dispatch({
      $type: 'offset_content',
      isAdd
    });
  }

  currentOffsetChangeHandler(e) {
    let value = parseInt(e.target.value.trim());
    if (isNaN(value)) {
      return;
    }

    value -= 1;

    if (value <= 0) {
      return;
    }
    if (value >= this.state.model.count) {
      return;
    }

    dispatcher.dispatch({
      $type: 'change_content_offset',
      value: value
    });
  }

  dateOtherClickHandler() {
    dispatcher.dispatch({
      $type: 'toggle_date_other_display'
    });
  }

  render() {

    let name = this.state.model.name||'--';
    let splitIndex = name.indexOf('(');

    return (
      <div className="pure-g">
        <div className="pure-u-1">
          <div className="box">
            <Card className="widget-float" title="ANR 问题描述" extra={<a className="close iconfont" href="#/">&#xe638;</a>}>
              <div className="pure-g">
                <div className="pure-u-1">
                  <div className="box">
                    <Card>
                      <table className="text-detail">
                        <tbody>
                          <tr key={1}>
                            <td style={{'width':'43%'}}>
                              {
                                splitIndex === -1
                                  ? name
                                  : (
                                    <div>
                                      {name.substr(0, splitIndex)}
                                      <br/>
                                      {name.substr(splitIndex)}
                                    </div>
                                  )
                              }
                            </td>
                            <td className="text-align-center" style={{'width':'33%'}}>
                              <div className="pure-g">
                                <div className="pure-u-1 pure-u-sm-1-4">
                                  <p><b>版本</b></p>
                                  <p>{this.state.model.appVersion||'--'}</p>
                                </div>
                                <div className="pure-u-1 pure-u-sm-1-4">
                                  <p><b>发生次数</b></p>
                                  <p>{this.state.model.count||'--'}</p>
                                </div>
                                <div className="pure-u-1 pure-u-sm-1-4">
                                  <p><b>影响用户</b></p>
                                  <p>{this.state.model.affected||'--'}</p>
                                </div>
                                <div className="pure-u-1 pure-u-sm-1-4">
                                  <p><b>ANR 率</b></p>
                                  <p>{this.state.anrRate||'--'}</p>
                                </div>
                              </div>
                            </td>
                            <td className="text-align-center" style={{'width':'23%'}}>
                              状态：&nbsp;&nbsp;
                              <label>
                                <input
                                  onChange={this.statusCodeChangeHandler}
                                  checked={this.state.model.statusCode === 0}
                                  type="radio"
                                  name="resolved"
                                  value="0"
                                  style={{'wordBreak':'nowrap'}} />
                                未解决
                              </label>
                              &nbsp;&nbsp;&nbsp;&nbsp;
                              <label>
                                <input
                                  onChange={this.statusCodeChangeHandler}
                                  checked={this.state.model.statusCode === 1}
                                  type="radio"
                                  name="resolved"
                                  value="1" />
                                已解决
                              </label>
                            </td>
                          </tr>
                        </tbody>
                      </table>
                    </Card>
                  </div>
                </div>
              </div>
              <div className="pure-g">
                <div className="pure-u-1">
                  <div className="box">
                    <Card title={
                      <span>
                        ANR实时走势
                      </span>
                    } extra={
                      <div>
                        <div className="switch-group" style={{'margin': '2px 0px 0px'}}>
                          <a
                            href="javascript:;"
                            onClick={this.dateCheckHandler.bind(this, 'today')}
                            className={cx({active: this.state.chartLineDateCheckStatus['today']})}>
                            今天
                          </a>
                          <a
                            href="javascript:;"
                            onClick={this.dateCheckHandler.bind(this, 'yesterday')}
                            className={cx({active: this.state.chartLineDateCheckStatus['yesterday']})}>
                            昨天
                          </a>
                          <a
                            href="javascript:;"
                            onClick={this.dateOtherClickHandler.bind(this)}
                            className={cx({active: this.state.chartLineDateListSelectedValue!==null})}>
                            <span style={{ fontWeight: 'normal' }}>
                              { this.state.chartLineDateListSelectedValue
                                  ? _.find(this.state.chartLineDateList, (item) => item.value === this.state.chartLineDateListSelectedValue).label
                                  : '其它'
                              }
                            </span>
                            <i className="iconfont icon-btn-arrow">&#xe619;</i>
                          </a>
                        </div>
                        <div ref="dateOtherRoot" className="dropdown" style={{display: (this.state.chartLineDateListOpened ? 'block' : 'none')}}>
                          <div className="dropdown-main">
                            <ul>
                              {
                                this.state.chartLineDateList.map((item) => {
                                  return (<li key={'DropdownList-item-' + item.value}><a onClick={this.customDateCheckHandler.bind(this, item)}>{item.label}</a></li>);
                                })
                              }
                            </ul>
                          </div>
                        </div>
                      </div>
                    }>
                      <ChartWidget store={ this.state.chartLine } tooltipShared={true} tooltipFormat={this.state.chartLineformatter} chartSettings={this.state.chartLineSettings} />
                    </Card>
                  </div>
                </div>
              </div>
              <div className="pure-g">
                <div className="pure-u-1 pure-u-lg-1-2">
                  <div className="box">
                    <Card title="设备分布">
                      <ChartWidget height={300} chartType="pie" store={ this.state.chartPie } tooltipFormat={ this.state.chartPieFormatter } chartSettings={ this.state.chartSettings } />
                    </Card>
                  </div>
                </div>
                <div className="pure-u-1 pure-u-lg-1-2">
                  <div className="box">
                    <Card title="系统版本">
                      <ChartWidget height={300} chartType="pie" store={ this.state.chartPie2 } tooltipFormat={ this.state.chartPieFormatter } chartSettings={ this.state.chartSettings } />
                    </Card>
                  </div>
                </div>
              </div>
              <div className="pure-g">
                <div className="pure-u-1">
                  <div className="box">
                    <Card>
                      <div className="text-align-center">最近一次ANR发生时间：{moment(this.state.model.lastTime).format('YYYY-MM-DD HH:mm')}</div>
                    </Card>
                  </div>
                </div>
              </div>
              <div className="pure-g">
                <div className="pure-u-1">
                  <div className="box">
                    <Card>
                      <div className="trace-cross-title">
                          <span className="previous" onClick={this.contentOffsetHandler.bind(this, false)}>
                            <a href="javascript:;" className="iconfont">&#xe658;</a>
                          </span>
                          <h4>
                            <p>
                              第&nbsp;
                              {this.state.contentOffset + 1}
                              /{this.state.model.count}个同类&nbsp;ANR
                            </p>
                            <p>{'发生时间：' + setup(this.state.content.timestamp, (value) => moment(value).format('YYYY-MM-DD HH:mm'), '--')}</p>
                          </h4>
                          <span className="next" onClick={this.contentOffsetHandler.bind(this, true)}>
                            <a href="javascript:;" className="iconfont">&#xe659;</a>
                          </span>
                        </div>
                    </Card>
                  </div>
                </div>
              </div>
              <div className="pure-g">
                <div className="pure-u-1">
                  <div className="box">
                    <Card>
                      <div className="pure-g">
                        <div className="pure-u-1 pure-u-lg-1-3">
                          包名：{this.state.content.occurPackage||'--'}
                        </div>
                        <div className="pure-u-1 pure-u-lg-2-3">
                          ANR 部件：{setup(this.state.content.occurLocation, (value) => value.indexOf('/') === -1 ? value : value.substr(value.indexOf('/') + 1), '--')}
                        </div>
                        <div className="pure-u-1 pure-u-lg-1-3">
                          设备信息：{this.state.content.model||'--'}
                        </div>
                        <div className="pure-u-1 pure-u-lg-1-3">
                          操作系统：{this.state.content.osNameAndVersion||'--'}
                        </div>
                        <div className="pure-u-1 pure-u-lg-1-3">
                          是否 ROOT：{setup(this.state.content.root, (value) => value === 1 ? '有' : '无', '--')}
                        </div>
                        <div className="pure-u-1 pure-u-lg-1-3">
                          可用内存：{setup(this.state.content.freeMemory, (value) => storageDisplay(value), '--')}
                        </div>
                        <div className="pure-u-1 pure-u-lg-1-3">
                          可用磁盘：{setup(this.state.content.freeSpace, (value) => storageDisplay(value), '--')}
                        </div>
                        <div className="pure-u-1 pure-u-lg-1-3">
                          可用 SD 卡：{setup(this.state.content.sdcardAvai, (value) => storageDisplay(value), '--')}
                        </div>
                        <div className="pure-u-1 pure-u-lg-1-3">
                          渠道信息：{this.state.content.channel||'--'}
                        </div>
                        <div className="pure-u-1 pure-u-lg-1-3">
                          SDK 信息：{this.state.content.sdkInfo||'--'}
                        </div>
                      </div>
                    </Card>
                  </div>
                </div>
              </div>
              <div className="pure-g">
                <div className="pure-u-1">
                  <div className="box">
                    <Card>
                      <Tab>
                        <Tab.Panel title="ANR 线程" key="anr_thread">
                          <table className="table table-striped">
                            <tbody>
                            {
                              setup(this.state.content.stackTrace, (value) => <tr><td><b style={{'color':'red'}}>{this.state.content.occurLocation}</b></td></tr>, null)
                            }
                            {
                              setup(this.state.content.stackTrace, (value) => _.chain(value.split('\n')).filter((item) => item).map((item, index) => {
                                return (
                                  <tr key={index}>
                                    <td style={{'paddingLeft': '20px'}}>{item.trim()}</td>
                                  </tr>
                                );
                              }).value(), null)
                            }
                            </tbody>
                          </table>
                        </Tab.Panel>
                        <Tab.Panel title="其它线程" key="other_thread">
                          <table className="table table-striped">
                            <tbody>
                            {
                              setup(this.state.content.otherThreads, (value) => _.chain(value.split('\n')).filter((item) => item).map((item, index) => {
                                if (item.indexOf('#') === 0) {
                                  return (
                                    <tr key={index}>
                                      <td><b>{item.trim()}</b></td>
                                    </tr>
                                  );
                                } else {
                                  return (
                                    <tr key={index}>
                                      <td style={{'paddingLeft': '20px'}}>{item.trim()}</td>
                                    </tr>
                                  );
                                }
                              }).value(), null)
                            }
                            </tbody>
                          </table>
                        </Tab.Panel>
                        <Tab.Panel title="ANR Trace 文件" key="anr_trace_file">
                          <table className="table table-striped">
                            <tbody>
                            {
                              setup(this.state.content.trace, (value) => _.chain(value.split('\n')).filter((item) => item).map((item, index) => {
                                if (item.indexOf('"') === 0 && item.indexOf('tid=') !== -1) {
                                  return (
                                    <tr key={index}>
                                      <td><b>{item.trim()}</b></td>
                                    </tr>
                                  );
                                } else {
                                  return (
                                    <tr key={index}>
                                      <td style={{'paddingLeft': '20px'}}>{item.trim()}</td>
                                    </tr>
                                  );
                                }
                              }).value(), null)
                            }
                            </tbody>
                          </table>
                        </Tab.Panel>
                        <Tab.Panel title="ANR Message" key="anr_message">
                          <table className="table table-striped">
                            <tbody>
                            {
                              setup(this.state.content.message, (value) => _.chain(value.split('\n')).filter((item) => item).map((item, index) => {
                                return (
                                  <tr key={index}>
                                    <td><span style={{'display':'inline-block', 'width':'40px'}}>{index+1}</span>{item.trim()}</td>
                                  </tr>
                                );
                              }).value(), null)
                            }
                            </tbody>
                          </table>
                        </Tab.Panel>
                      </Tab>
                    </Card>
                  </div>
                </div>
              </div>
            </Card>
          </div>
        </div>
      </div>
    )
  }
}

DetailView.defaultProps = {
  Scope:DetailScope
}
